package com.htfyun.ft.agingtest;

import android.content.Context;
import android.os.Message;
import android.os.PowerManager;

import com.htfyun.ft.R;
import com.htfyun.ft.config.NVRomKeysAttr;
import com.htfyun.ft.device.DeviceAttr;
import com.htfyun.ft.utils.DebugLog;
import com.htfyun.ft.utils.TimeStringUtils;
import com.htfyun.ft.utils.UsefulUtils;


public class TestReboot extends AgingTestItemBase {

    private static final int MSG_COUNT_DOWN = 100;
    private static final int PERIOD_COUNT_DOWN = 1000;
    private static final int MSG_REBOOT = 200;

    private int countDown = 20;

    private TestHardDiskRWManager hardDiskRWManager = null;
    private boolean hardDiskError = false;
    private boolean hardDiskTestOver = false;
    private StringBuilder hardDiskInfoBuilder ;

    public TestReboot() {

        if (getAgingTestItemAttr() != null
                && getAgingTestItemAttr().isTestOver()
                && AgingBooleanSettingsAttr.reboot_started.get()
                ) {

            super.setTestStarted(true);

        }
    }

    private void appendHardDiskInfo(String info) {
        if (hardDiskInfoBuilder != null) {
            hardDiskInfoBuilder.append(info);
            hardDiskInfoBuilder.append("\n");
        }
    }
    private void initHardDiskManager() {
        if (!DeviceAttr.isNVRomKeySupported(NVRomKeysAttr.hard_disk)) {
            return;
        }
        if (hardDiskRWManager != null) {
            return;
        }

        hardDiskError = false;
        hardDiskTestOver = false;
        hardDiskInfoBuilder = new StringBuilder();
        hardDiskRWManager = new TestHardDiskRWManager(getContext());

        hardDiskRWManager.setOnRWListener(new TestHardDiskRWManager.OnRWListener() {
            @Override
            public void onReadAction(String path, String log) {
                appendHardDiskInfo(log);
            }

            @Override
            public void onWriteAction(String path, String log) {
                appendHardDiskInfo(log);
            }

            @Override
            public void onTestOver() {
                if (!hardDiskError) {
                    getHandler().sendEmptyMessageDelayed(MSG_COUNT_DOWN, PERIOD_COUNT_DOWN);
                    hardDiskTestOver = true;
                }
            }

            @Override
            public void onDeleteOver() {
                appendHardDiskInfo("onDeleteOver");

                hardDiskRWManager.startTest(1,1);

                appendHardDiskInfo("start test hard disk RW");

            }

            @Override
            public void onRWCompletedAction(String rootPath) {

                appendHardDiskInfo(rootPath + ", test completed");
            }

            @Override
            public void onError(String path, String log) {

                appendHardDiskInfo(log);
                hardDiskError = true;
            }
        });
    }

    @Override
    protected void handleMessage(Message msg) {
        final int what = msg.what;
        switch (what) {
            case MSG_COUNT_DOWN:
                updateCountdown();
                break;
            case MSG_REBOOT:
                reboot();
                break;
        }
    }

    @Override
    protected void doStartTest() {
        DebugLog.e("TestReboot doStartTest");
        if (DeviceAttr.isNVRomKeySupported(NVRomKeysAttr.hard_disk)) {
            initHardDiskManager();
            hardDiskRWManager.deleteWritten();
        } else {
            updateCountdown();
        }
    }

    @Override
    protected void doStopTest() {
        DebugLog.e("TestReboot doStopTest");
        getHandler().removeMessages(MSG_COUNT_DOWN);

        if (DeviceAttr.isNVRomKeySupported(NVRomKeysAttr.hard_disk)) {
            if (hardDiskRWManager != null) {
                hardDiskRWManager.setOnRWListener(null);
                hardDiskRWManager.stopTest();
                hardDiskRWManager = null;
                hardDiskInfoBuilder = null;
            }
        }
    }

    @Override
    public AgingTestItemAttr getAgingTestItemAttr() {
        return AgingTestItemAttr.reboot;
    }

    @Override
    public CharSequence getInfoString() {

        if (DeviceAttr.isNVRomKeySupported(NVRomKeysAttr.hard_disk) && !hardDiskTestOver) {
            return hardDiskInfoBuilder.toString();
        }

        long usedTime = AgingLongSettingsAttr.aging_time_tick.get() - getAgingTestItemAttr().getStartTime_ms();

        String timeStr = TimeStringUtils.makeTimeString(usedTime);

        String info = getContext().getString(R.string.aging_reboot_info, countDown,
                getAgingTestItemAttr().getTestCount(),
                timeStr);

        long startTimeOfReboot = getAgingTestItemAttr().getStartTimeAbsolute_ms();
        long now = System.currentTimeMillis();

        String timeInfo = getContext().getString(R.string.aging_reboot_time_info,
                UsefulUtils.millis2String(startTimeOfReboot),
                UsefulUtils.millis2String(now));

        String returnInfo = (info + "\n" + timeInfo);
        if (DeviceAttr.isNVRomKeySupported(NVRomKeysAttr.hard_disk) && hardDiskInfoBuilder != null) {
            returnInfo = hardDiskInfoBuilder.toString() + "\n" + returnInfo;
        }
        return returnInfo;
    }

    @Override
    protected void setTestStarted(boolean started) {
        super.setTestStarted(started);
        AgingBooleanSettingsAttr.reboot_started.set(started);
    }

    private void updateCountdown() {

        countDown -= PERIOD_COUNT_DOWN / 1000;

        if (countDown <= 0) {
            getHandler().sendEmptyMessage(MSG_REBOOT);
        } else {
            getHandler().sendEmptyMessageDelayed(MSG_COUNT_DOWN, PERIOD_COUNT_DOWN);
        }
    }

    private void reboot() {

        getAgingTestItemAttr().addOneTestCount();

        PowerManager pManager = (PowerManager) getContext().getSystemService(Context.POWER_SERVICE);
        if (pManager != null) {
            pManager.reboot(null);
            DebugLog.e("reboot now");
        }
    }
}
